/**
 * 佣金管理服务
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    require("pagination");
    var util = require("util");
    var ui = require("ui");
    var dialog = require("dialog");
    var angular = require("angular");

    var brokerageModule = angular.module('brokerageModule', []);

    // 统一查询服务
    function queryService($http, $q, baseData) {
        var service = {
            data: [],
            hasData: true,
            checkAll: false,
            pageIndex: 1,
            pageSize: 10,

            // 全选/取消全选
            updateCheckAll: function () {
                for (var i = 0; i < service.data.length; i++) {
                    service.data[i].checked = service.checkAll;
                }
            },

            // 同步全选/取消全选
            updateCheck: function (record) {
                var checked = true;
                for (var i = 0; i < service.data.length; i++) {
                    if (!service.data[i].checked) {
                        checked = false;
                        break;
                    }
                }

                service.checkAll = checked;
            },

            // 导出
            exportData: function (filters) {
                if (!baseData.projectId) {
                    return;
                }

                filters = service.getFilters(filters);
                delete filters.pageIndex;
                delete filters.pageSize;
                var url = '/api/index.php?r=qmyx/brokerage/export&token=' + util.getToken();
                url += '&' + $.param(filters);
                window.location.href = url;
            },

            // 导入
            importData: function () {

            },

            getFilters: function (filters) {
                filters = filters || {};
                filters.p_projectId = baseData.projectId;
                filters.pageSize = service.pageSize;
                filters.brokerage_type = baseData.brokerageType;
                if (baseData.brokerageState == 1) {
                    filters.isApproval = 0;
                    filters.isoffer = 0;
                }
                else if (baseData.brokerageState == 2) {
                    filters.isApproval = 1;
                    filters.isoffer = 0;
                }
                else if (baseData.brokerageState == 3) {
                    filters.isApproval = 1;
                    filters.isoffer = 1;
                }

                return filters;
            },

            doQuery: function (filters, pageIndex) {
                filters = service.getFilters(filters);
                filters.pageIndex = pageIndex || 1;
                var url = '/api/index.php?r=qmyx/brokerage/getlist';
                url += '&' + $.param(filters);

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.get(url, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.data = data.data.data;
                        service.checkAll = false;
                        service.hasData = !!service.data.length;
                        service.pageIndex = filters.pageIndex;
                        service.total = data.data.total;
                    });
            }
        };

        return service;
    }
    brokerageModule.factory('query', ['$http', '$q', 'baseData', queryService]);

    // 过滤条件服务
    function filterService($http, query, baseData) {
        var service = {
            // 起始时间
            startDate: '',
            // 结束时间
            endDate: '',

            query: function (pageIndex) {
                if (!baseData.projectId) {
                    return;
                }

                baseData.currentQueryService = service;
                query.doQuery(service.getFilters(), pageIndex);
            },

            exportData: function () {
                if (!baseData.projectId) {
                    return;
                }

                query.exportData(service.getFilters());
            },

            getFilters: function() {
                var filters = {};
                filters['capacity_des'] = baseData.selectedBrokerIdentity;

                if (baseData.owerCompanys && baseData.owerCompanys.length) {
                    var owerCompanyIds = [];
                    for (var i = 0; i < baseData.owerCompanys.length; i++) {
                        if (baseData.owerCompanys[i].checked) {
                            owerCompanyIds.push(baseData.owerCompanys[i].Value);
                        }
                    }
                    filters['belongs_company'] = JSON.stringify(owerCompanyIds);
                }

                filters['start_time'] = service.startDate;
                filters['end_time'] = service.endDate;

                return filters;
            },

            // 撤销过滤
            clearFilter: function () {
                baseData.selectedBrokerIdentity = '';
                baseData.owerCompanys = [];
                service.startDate = '';
                service.endDate = '';

                service.query();
            }
        };

        return service;
    }
    brokerageModule.factory('filter', ['$http', 'query', 'baseData', filterService]);

    // 简单查询服务
    function searchSerivce(query, baseData) {
        var service = {
            fieldList: [
                { value: 'c_broker_name', text: '被邀经纪人姓名' },
                { value: 'c_broker_tel', text: '被邀经纪人电话' },
                { value: 'broker_name', text: '经纪人姓名' },
                { value: 'broker_tel', text: '经纪人电话' }
            ],
            // 查询字段
            field: 'c_broker_name',
            // 关键字
            keyword: '',

            getFilters: function () {
                var filters = {};
                filters[service.field] = service.keyword;
                return filters;
            },

            query: function (pageIndex) {
                if (!baseData.projectId) {
                    return;
                }

                baseData.currentQueryService = service;
                query.doQuery(service.getFilters(), pageIndex);
            },

            exportData: function () {
                if (!baseData.projectId) {
                    return;
                }

                query.exportData(service.getFilters());
            }
        };

        return service;
    }
    brokerageModule.factory('search', ['query', 'baseData', searchSerivce]);

    // 基础数据服务（项目列表、经纪人身份等）
    function baseDataService($http, $q) {
        var service = {
            // 基础数据是否加载
            loaded: false,
            // 是否开启佣金代支付
            allowBrokeragePayment: 0,
            // 经纪人身份
            brokerIdentitys: [],
            // 所属公司
            owerCompanys: [],
            // 项目列表
            projectList: [],
            // 当前查询服务（search、filter）
            currentQueryService: null,
            // 选中所有所属公司
            owerCompanyCheckAll: false,
            // 佣金类型
            brokerageType: -1,
            // 佣金状态
            brokerageState: -1,

            // 统一查询
            query: function (pageIndex) {
                if (service.currentQueryService) {
                    service.currentQueryService.query(pageIndex);
                }
            },

            // 统一导出，使用查询的结果
            exportData: function () {
                if (service.currentQueryService) {
                    service.currentQueryService.exportData();
                }
            },

            // 获取佣金类型文本
            getBrokerageTypeText: function () {
                switch (service.brokerageType) {
                    case 3:
                        return '邀请';
                    case 4:
                        return '成交';
                }

                return '邀请';
            },

            // 获取时间标签文本
            getDateLabelText: function () {
                if (service.brokerageType == 4) {
                    return '奖励产生时间：';
                } else {
                    return '成功邀请时间：';
                }
            },

            // 切换经纪人身份
            changeBrokerIdentity: function (event, value) {
                service.selectedBrokerIdentity = value;
                service.owerCompanys = service.getOwerCompanys();
                for (var i = 0; i < service.owerCompanys.length; i++) {
                    service.owerCompanys[i].checked = false;
                }
                service.owerCompanyCheckAll = false;
                if (event) {
                    ui.changeTipsArrow(event.currentTarget);
                }
            },

            // 获取所属公司
            getOwerCompanys: function () {
                switch (service.selectedBrokerIdentity) {
                    case '9003':
                        // 代理公司
                        return service.agentCompany || [];

                    case '9005':
                        // 中介公司
                        return service.agencyCompany || [];

                    case '9006':
                        // 合作伙伴
                        return service.partnerCompany || [];

                    case '9108':
                        // 中介机构
                        return service.agency || [];

                    default:
                        return [];
                }
            },

            // 全选/取消全选
            updateOwerCompanyCheckAll: function () {
                for (var i = 0; i < service.owerCompanys.length; i++) {
                    service.owerCompanys[i].checked = service.owerCompanyCheckAll;
                }
            },

            // 同步全选/取消全选
            updateOwerCompanyCheck: function (record) {
                var checked = true;
                for (var i = 0; i < service.owerCompanys.length; i++) {
                    if (!service.owerCompanys[i].checked) {
                        checked = false;
                        break;
                    }
                }

                service.owerCompanyCheckAll = checked;
            },

            // 初始化查询表单数据
            initData: function () {
                var promises = [
                    // 是否开启佣金代支付
                    $http.get('/api/index.php?r=qmyx/brokerage/allow-entrusted-payment'),
                    // 获取经纪人身份列表
                    $http.get('/api/index.php?r=qmyx/broker/get-broker-identity-by-token'),
                    // 项目列表
                    $http.get('/api/index.php?r=qmyx/customer-manage/get-project-list'),
                    // 合作伙伴
                    $http.get('/api/index.php?r=qmyx/broker/get-companys-by-token-and-code&paramCode=partnerCompany'),
                    // 代理公司
                    $http.get('/api/index.php?r=qmyx/broker/get-companys-by-token-and-code&paramCode=agentCompany'),
                    // 中介公司
                    $http.get('/api/index.php?r=qmyx/broker/get-companys-by-token-and-code&paramCode=agencyCompany'),
                    // 中介机构
                    $http.get('/api/index.php?r=qmyx/broker/get-companys-by-token-and-code&paramCode=agency')
                ];

                return $q.all(promises).then(function (xhrs) {
                    var i = 0;
                    service.allowBrokeragePayment = xhrs[i++].data.data ? 1 : 0;
                    service.brokerIdentitys = xhrs[i++].data.data;
                    service.projectList = xhrs[i++].data.data;
                    service.partnerCompany = xhrs[i++].data.data;
                    service.agentCompany = xhrs[i++].data.data;
                    service.agencyCompany = xhrs[i++].data.data;
                    service.agency = xhrs[i++].data.data;

                    //service.projectId = service.projectId || service.projectList && service.projectList[0] && service.projectList[0].p_projectId
                    //    || '';
                    //if (!service.projectId) {
                    //    return;
                    //}
                    service.loaded = true;
                });
            }
        };

        return service;
    }
    brokerageModule.factory('baseData', ['$http', '$q', baseDataService]);

    // 佣金服务
    function brokerageSerivce($http, $filter, baseData, query) {
        var service = {
            // 执行审定
            approve: function (record) {
                var data = {
                    amount: record.amount,
                    b_regbroker_brokerageId: record.b_regbroker_brokerageId,
                    brokerage_type: baseData.brokerageType,
                    regbroker_cst_trade_recordId: record.b_regbroker_cst_trade_recordId
                };

                var url = '/api/index.php?r=qmyx/brokerage/approval';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });

            },

            // 显示批量审定
            showBatchApprove: function () {
                var batchApproveData = [];
                var totalAmount = 0;

                for (var i = 0; i < query.data.length; i++) {
                    if (query.data[i].checked) {
                        var amount = parseFloat(query.data[i].amount) || 0;

                        totalAmount += amount;
                        batchApproveData.push({
                            b_regbroker_brokerageId: query.data[i].b_regbroker_brokerageId,
                            amount: query.data[i].amount,
                            regbroker_cst_trade_recordId: query.data[i].b_regbroker_cst_trade_recordId
                        });
                    }
                }

                if (batchApproveData.length) {
                    var msg = '批量审批 ' + batchApproveData.length + ' 笔，奖励总额 ' + $filter('number')(totalAmount) + ' 元，确定审定选中的记录吗？';
                    util.confirm(msg, {
                        ok: function () {
                            service.batchApprove(batchApproveData);
                        }
                    });
                } else {
                    util.alert('请选择要操作的记录');
                }
            },

            // 执行批量审定
            batchApprove: function (batchApproveData) {
                var data = {
                    batch: batchApproveData,
                    brokerage_type: baseData.brokerageType
                };
                var url = '/api/index.php?r=qmyx/brokerage/approval';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 取消审定
            cancelApprove: function (record) {
                var data = {
                    b_regbroker_brokerageId: record.b_regbroker_brokerageId,
                    brokerage_type: baseData.brokerageType
                };

                var url = '/api/index.php?r=qmyx/brokerage/cancel-approval';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 发放
            offer: function (record) {
                var data = {
                    amount: record.amount,
                    b_regbroker_brokerageId: record.b_regbroker_brokerageId,
                    brokerage_type: baseData.brokerageType
                };

                var url = '/api/index.php?r=qmyx/brokerage/pay';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 取消发放
            cancelOffer: function (record) {
                var data = {
                    b_regbroker_brokerageId: record.b_regbroker_brokerageId,
                    brokerage_type: baseData.brokerageType
                };

                var url = '/api/index.php?r=qmyx/brokerage/cancel-pay';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 显示批量发放
            showBatchOffer: function () {
                var data = [];
                for (var i = 0; i < query.data.length; i++) {
                    if (query.data[i].checked) {
                        data.push({
                            b_regbroker_brokerageId: query.data[i].b_regbroker_brokerageId
                        });
                    }
                }

                if (data.length) {
                    util.confirm('确定批量发放所选奖励吗？', {
                        ok: function () {
                            service.batchOffer(data);
                        }
                    });
                } else {
                    util.alert('请选择要操作的记录');
                }
            },

            // 执行批量发放
            batchOffer: function (brokerages) {
                var data = {
                    brokerage_type: baseData.brokerageType,
                    batch: brokerages
                };
                var url = '/api/index.php?r=qmyx/brokerage/pay';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 显示批量委托发放
            showBatchPay: function () {
                var data = [];
                var totalAmount = 0;
                for (var i = 0; i < query.data.length; i++) {
                    if (query.data[i].checked) {
                        totalAmount += parseFloat(query.data[i].amount) || 0;
                        data.push(query.data[i].b_regbroker_brokerageId);
                    }
                }

                if (data.length) {
                    // util.confirm('确定批量委托发放所选奖励吗？', {
                    //     ok: function () {
                    //         service.batchPay(data);
                    //     }
                    // });
                    var msg = '批量委托发放 ' + data.length + ' 笔，佣金总额 ' + $filter('number')(totalAmount) + ' 元，您确定委托发放吗？';
                    util.confirm(msg, {
                        ok: function () {
                            service.batchPay(data);
                        }
                    });
                } else {
                    util.alert('请选择要操作的记录');
                }
            },

            // 执行批量委托发放
            batchPay: function(brokerages) {
                var data = {
                    brokerageIds: brokerages
                };
                var url = '/api/index.php?r=qmyx/brokerage/entrust-pay';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 委托发放
            pay: function (record) {
                var data = {
                    brokerageIds: [record.b_regbroker_brokerageId]
                };

                var url = '/api/index.php?r=qmyx/brokerage/entrust-pay';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            }
        };

        return service;
    }
    brokerageModule.factory('brokerage', ['$http', '$filter', 'baseData', 'query', brokerageSerivce]);
    
    module.exports = brokerageModule;
});